<?php

namespace Summer\Hjd\Http\Controllers;

use Illuminate\Routing\Controller;
use Illuminate\Support\Carbon;
use RainLab\User\Models\User as UserModel;
use RLuders\JWTAuth\Classes\JWTAuth;
use Input;
use Db;
use Event;
use Exception;
use ApplicationException;
use RLuders\JWTAuth\Models\User as UserJwtModel;
use Summer\Hjd\Http\Requests\BindMobileRequest;
use Summer\Hjd\Http\Requests\ForgotPwdRequest;
use Summer\Hjd\Http\Requests\SmsLoginRequest;
use Summer\Hjd\Http\Requests\UpdatePwdRequest;
use Summer\Hub\Http\Controllers\Traits\ApiReturn;
use Summer\Sms\Classes\CodeApi;
use Summer\Userhub\Models\OauthModel;
use System\Models\File as FileModel;
use Tymon\JWTAuth\Exceptions\JWTException;


class UserController extends Controller
{
    use ApiReturn;

    public function thirdOauthInfo(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $platform = request()->header('platform');
        $userOauth=OauthModel::where('platform',$platform)->where('user_id',$user->id)->first();
        return $this->apiSuccess('操作成功',$userOauth);

    }

    /**
     * 个人中心
     * @param JWTAuth $auth
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $query=UserModel::select();
        $query->with([
            'avatar',
            'oauth',
            'leveluinfo'=>function($q){
                $q->select('id','title');
            },
            'tuijianinfo'=>function($q){
                $q->select('id','username','userphone','realname','nickname');
            },
            'wallets'=>function($q){
                $q->select('id','currency_slug','user_id','balance');
                $q->with(['currency'=>function($qc){
                    $qc->select('id','slug','title');
                }]);
                $q->whereHas('currency',function ($qhc){
                    $qhc->where('status',1);
                });
            },
            //居住地址信息，后期加开关
            'province'=>function($q){$q->select('code','name');},
            'city'=>function($q){$q->select('code','name');},
            'area'=>function($q){$q->select('code','name');},
            'town'=>function($q){$q->select('code','name');},
        ]);
        $query->where('id',$user->id);
        $userinfo=$query->first();

        //验证信息
        $verification=[];
        if($userinfo->userphone){//手机号
            $verification['userphone']=1;
        }else{
            $verification['userphone']=0;

        }
        if($userinfo->email){//邮箱
            $verification['email']=1;
        }else{
            $verification['email']=0;
        }
        $verification['wxMiniProgram']=0;//小程序绑定
        $verification['wxOfficialAccount']=0;//公众号绑定
        if(!empty($userinfo->oauth)){
            foreach ($userinfo->oauth as $uo){
                $verification[$uo['platform']]=1;
            }
        }
        $userinfo['verification']=$verification;
        $rdata['userinfo']=$userinfo;
        return $this->apiSuccess('操作成功',$rdata);
    }


    /**
     * 修改用户信息
     * @param JWTAuth $auth
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }

        $pdata=Input::all();
        $udata=[];
        if(!empty($pdata['realname'])&&$pdata['realname']!=$user->realname){
            $udata['realname']=$pdata['realname'];
        }
        if(!empty($pdata['nickname'])&&$pdata['nickname']!=$user->nickname){
            $udata['nickname']=$pdata['nickname'];
        }
        if(!empty($pdata['birthday'])&&$pdata['birthday']!=$user->birthday){
            $udata['birthday']=$pdata['birthday'];
        }
        //居住地址信息
        if(!empty($pdata['province_code'])&&$pdata['province_code']!=$user->province_code){
            $udata['province_code']=$pdata['province_code'];
        }
        if(!empty($pdata['city_code'])&&$pdata['city_code']!=$user->city_code){
            $udata['city_code']=$pdata['city_code'];
        }
        if(!empty($pdata['area_code'])&&$pdata['area_code']!=$user->area_code){
            $udata['area_code']=$pdata['area_code'];
        }
        if(!empty($pdata['town_code'])&&$pdata['town_code']!=$user->town_code){
            $udata['town_code']=$pdata['town_code'];
        }
        if(!empty($pdata['address'])&&$pdata['address']!=$user->address){
            $udata['address']=$pdata['address'];
        }


        if(!empty($udata)){
            try {
                UserModel::where('id',$user->id)->update($udata);
            }
            catch (Exception $e){
                return $this->apiError($e->getMessage());
            }
        }
        //上传图片，文件系统需要定位到到是RainLab\User\Models\User，而不是RLuders\JWTAuth\Models\User，所以需要重新获取下
        $user=UserModel::where('id',$user->id)->first();
        //如果上传了图片
        if(Input::has('avatar_id')){
            $avatar_id=Input::get('avatar_id');
            $avatar_cover=FileModel::where('id',$avatar_id)->first();
            $user->avatar()->add($avatar_cover);
        }


        return $this->apiSuccess('操作成功');
    }

    /**
     * 收款信息
     */
    public function bankInfo(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $type=Input::get('type');
        $field=[];
        if($type=='bank'){
            $field=['bank_name','bank_number','bank_address','realname'];
        }
        if($type=='wechat'){
            $field=['wechat_number','realname'];
        }
        if($type=='alipay'){
            $field=['alipay_number','realname'];
        }
        $query=UserModel::select($field);
        $query->where('id',$user->id);
        $bank_info=$query->first();
        return $this->apiSuccess('操作成功',$bank_info);
    }

    /**
     * 修改用户收款信息
     */
    public function updateBank(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $pdata=Input::all();

        $mobile=$user->userphone;
        $code=$pdata['code'];
        //密码验证
        $code_api=new CodeApi();
        $code_res=$code_api->check($mobile,$code);
        if($code_res['status']<0){
            return $this->apiError('操作失败：'.$code_res['msg']);
        }

        $udata=[];
        //有短信验证了，去掉这个限制
//        if($user->bank_number||$user->bank_address||$user->bank_address){
//            return $this->apiError('只能首次添加，修改请联系后台管理员');
//        }
        if(!empty($pdata['bank_name'])&&$pdata['bank_name']!=$user->bank_address){
            $udata['bank_name']=$pdata['bank_name'];
        }
        if(!empty($pdata['bank_number'])&&$pdata['bank_number']!=$user->bank_number){
            $udata['bank_number']=$pdata['bank_number'];
        }
        if(!empty($pdata['bank_address'])&&$pdata['bank_address']!=$user->bank_address){
            $udata['bank_address']=$pdata['bank_address'];
        }
        if(!empty($pdata['wechat_number'])&&$pdata['wechat_number']!=$user->wechat_number){
            $udata['wechat_number']=$pdata['wechat_number'];
        }
        if(!empty($pdata['alipay_number'])&&$pdata['alipay_number']!=$user->alipay_number){
            $udata['alipay_number']=$pdata['alipay_number'];
        }
        if(!empty($udata)){
            try {
                UserModel::where('id',$user->id)->update($udata);
            }
            catch (Exception $e){
                return $this->apiError($e->getMessage());
            }
        }
        //上传图片，文件系统需要定位到到是RainLab\User\Models\User，而不是RLuders\JWTAuth\Models\User，所以需要重新获取下
        $user=UserModel::where('id',$user->id)->first();
        if(Input::has('wechat_cover_id')){
            $wechat_cover_id=Input::get('wechat_cover_id');
            $wechat_cover=FileModel::where('id',$wechat_cover_id)->first();
            $user->wechat_cover()->add($wechat_cover);
        }
        if(Input::has('alipay_cover_id')){
            $alipay_cover_id=Input::get('alipay_cover_id');
            $alipay_cover=FileModel::where('id',$alipay_cover_id)->first();
            $user->alipay_cover()->add($alipay_cover);
        }
        return $this->apiSuccess('操作成功');

    }


    /**
     * 修改密码
     * @param JWTAuth $auth
     * @param UpdatePwdRequest $request
     * @return array
     */
    public function updatePwd(JWTAuth $auth,UpdatePwdRequest $request){
        $request->validate();
        $user = $auth->user();
        $pdata=$request->data();
        $type=$pdata['type'];

        if($type=='login'){
            if (!$user->checkHashValue('password', $pdata['oldPwd'])) {
                return $this->apiError('原密码输入错误');
            }
            $data_save['password']=$pdata['newPwd'];
            //应该是哪里有验证确认密码的。暂时这样处理
            $data_save['password_confirmation']=$pdata['rePwd'];
        }
        if($type=='safe'){
            if (!$user->checkHashValue('password_safe', $pdata['oldPwd'])) {
                return $this->apiError('原密码输入错误');
            }
            $data_save['password_safe']=Input::get('newPwd');
        }
        $user->fill($data_save);
        $user->save();
        return $this->apiSuccess('操作成功');
    }

    /**
     * 找回密码
     * @param JWTAuth $auth
     * @param UpdatePwdRequest $request
     * @return array
     */
    public function forgotPwd(ForgotPwdRequest $request){
        $request->validate();
        $pdata=$request->data();
        $type=$pdata['type'];
        $mobile=$pdata['mobile'];
        $code=$pdata['code'];
        $password=$pdata['password'];

        //密码验证
        $code_api=new CodeApi();
        $code_res=$code_api->check($mobile,$code);
        if($code_res['status']<0){
            return $this->apiError('操作失败：'.$code_res['msg']);
        }
        $user=UserModel::where('userphone',$mobile)->first();
        if(!$user){
            return $this->apiError('没有该用户');
        }
        if($type=='login'){
            $data_save['password']=$password;
            $data_save['password_confirmation']=$password;
        }
        if($type=='safe'){
            $data_save['password_safe']=$password;
        }
        $user->fill($data_save);
        $user->save();
        return $this->apiSuccess('操作成功');
    }

    /**
     * 短信登录
     */
    public function smsLogin(JWTAuth $auth,SmsLoginRequest $request)
    {
        $request->validate();
        $pdata=$request->data();
        $mobile=$pdata['mobile'];
        $code=$pdata['code'];

        //短信验证
        $code_api=new CodeApi();
        $code_res=$code_api->check($mobile,$code);
        if($code_res['status']==2){
            return $this->apiError('短信登录未开通');
        }
        if($code_res['status']<0){
            return $this->apiError('操作失败：'.$code_res['msg']);
        }
        $user=UserJwtModel::where('userphone',$mobile)->first();
        if(!$user){
            return $this->apiError('没有该用户');
        }
        $token = $auth->fromUser($user);
        $user = $auth->setToken($token)->authenticate();
        return $this->apiSuccess('登录成功',compact('token', 'user'));
    }

    /**
     * 绑定更换手机号
     */
    public function bindMobile(JWTAuth $auth,BindMobileRequest $request)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $request->validate();
        $pdata=$request->data();
        $mobile=$pdata['mobile'];
        $code=$pdata['code'];
        //短信验证
        $code_api=new CodeApi();
        $code_res=$code_api->check($mobile,$code);
        if($code_res['status']<0){
            return $this->apiError('操作失败：'.$code_res['msg']);
        }
        $phone_user=UserModel::where('id','<>',$user->id)->where('userphone',$mobile)->first();
        if($phone_user){
            return $this->apiError('该手机号已绑定会员');
        }
        UserModel::where('id',$user->id)->update(['userphone'=>$mobile]);
        return $this->apiSuccess('登录成功');
    }

    /**
     * 我的团队
     * @param JWTAuth $auth
     * @return \Illuminate\Http\JsonResponse
     */
    public function myTeam(JWTAuth $auth){
        $user = $auth->user();
        $pdata=Input::all();
        $page=$pdata['page']??1;
        $page_size=$pdata['page_size']??20;
        $tdeep_min=$pdata['tdeep_min']??0;
        $tdeep_max=$pdata['tdeep_max']??0;
        //判断活跃
        $active_type=$pdata['active_type']??'active';
        //团队信息
        $userinfo=UserModel::select('num_zt','num_td','tuid','yeji_td')->with([
            'tuijianinfo'=>function($q){
                $q->select('id','username','userphone','realname','nickname');
            }
        ])->where('id',$user->id)->first();
        $rdata['userinfo']=$userinfo;
        //团队列表
        $query=UserModel::select('id','username','userphone','realname','nickname','tdeep','created_at');
        if($tdeep_min>0){
            $query->where('tdeep','>=',$user->tdeep+$tdeep_min);
        }
        if($tdeep_max>0){
            $query->where('tdeep','<=',$user->tdeep+$tdeep_max);
        }
        if($active_type=='active'){
            $query->where('yeji_self_total','>',0);
        }else{
            $query->where('yeji_self_total',0);
        }
        $records=$query->whereRaw("FIND_IN_SET(?,`tids`)",[$user->id])->paginate($page_size,$page);
        $records->each(function ($record)use($user){
            $record->tdeep_text='第'.($record->tdeep-$user->tdeep).'代';
        });
        $rdata['records']=$records;
        return $this->apiSuccess('操作成功',$rdata);
    }

    /**
     * 用户团队
     * @param JWTAuth $auth
     */
    public function userTeam(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $user_id=Input::get('user_id',$user->id);
        $page=Input::get('page',1);
        $page_size=Input::get('page_size',20);
        $query=UserModel::select();
        $query->where('tuid',$user_id);
        $query->orderBy('id','DESC');
        $records=$query->paginate($page_size,$page);
        $return['records']=$records;
        return $this->apiSuccess('操作成功',$return);
    }


    public function myShare(JWTAuth $auth){
        $user = $auth->user();
        $share_url=url('auth/registers',['tuijian_number'=>$user->referrer_code]);
        $rdata['referrer_code']=$user->referrer_code;
        $rdata['share_url']=$share_url;
        return $this->apiSuccess('操作成功',$rdata);
    }

    /**
     * 退出登录//目前的操作是刷新token但不返回
     * @param JWTAuth $auth
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout(JWTAuth $auth)
    {
        $user = $auth->user();
        $token=Input::get('token');
        $auth->setToken($token);
        try {
            if (!$token = $auth->refresh($token)) {
                return $this->apiError('操作失败');
            }
        } catch (Exception $e) {
            return $this->apiError('操作失败');
        }
        //这个操作是同时退出网页端登录
        if ($user) {
            Event::fire('rainlab.user.logout', [$user]);
        }
        return $this->apiSuccess('退出成功');
    }

}
